<template>
  <div>
    <el-row :gutter="10" style="margin: 10px;">
      <!-- 工程、案卷信息 -->
      <el-col :span="8">
        <el-card style="height: 780px" v-loading="engLoading">
          <div slot="header" class="search-header">
            <div class="show_title">工程目录：</div>
            <div class="flex-container"> <!-- 使用 Flexbox 布局 -->
              <el-input
                v-model="engQueryParams.gcName"
                placeholder="搜索工程"
                clearable
                @keyup.enter.native="searchEng"
                class="my_input"
              />
              <div class="button-group">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="searchEng"
                >搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetEng">重置</el-button>
              </div>
            </div>
          </div>
          <ul class="engs-container">
            <li v-for="eng in engList" :key="eng.id">
              <span class="eng-row" @click="toggleEng(eng)" :class="{ selected: eng === selectedEng }">
                <i class="folder-icon eng-folder-icon"></i>
                <span class="folder-name">{{ eng.gcName }}</span>
              </span>
              <ul v-show="eng.expanded">
                <li v-for="anJuan in eng.anjuanList" :key="anJuan.id" style="list-style: none;">
                    <span class="anjuan-row" @click="selectanJuan(anJuan)"
                          :class="{ selected: anJuan === selectedAnJuan }">
                      <i class="folder-icon anJuan-folder-icon"></i>
                      <span class="folder-name">{{ anJuan.gccreelName }}</span>
                    </span>
                </li>
              </ul>
            </li>
          </ul>
          <div class="pagination-container">
            <!-- 分页信息 -->
            <el-pagination
              @size-change="handleSizeChangeEng"
              @current-change="handleCurrentChangeEng"
              :current-page.sync="engQueryParams.pageNum"
              :page-size.sync="engQueryParams.pageSize"
              small
              layout="total, prev, pager, next, jumper"
              :pager-count="5"
              :total="engTotal"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
      <!-- 文件信息-->
      <el-col :span="9">
        <el-card style="height: 780px" v-loading="fileLoading">
          <div slot="header" class="search-header">
            <div class="show_title">文件列表：</div>
            <div class="flex-container"> <!-- 使用 Flexbox 布局 -->
              <el-input
                v-model="fileQueryParams.gccatalogueName"
                placeholder="搜索文件"
                clearable
                @keyup.enter.native="searchFile"
                class="my_input"
              />
              <div class="button-group">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="searchFile">搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetFile">重置</el-button>
              </div>
            </div>
          </div>
          <ul class="engs-container">
            <li v-for="file in fileList" :key="file.id">
              <span class="eng-row" @click="selectFile(file)" :class="{ selected: file === selectedWenJian }">
                <i class="folder-icon file-folder-icon"></i>
                <span class="folder-name">{{ file.gccatalogueName }}</span>
              </span>
            </li>
          </ul>
          <div class="pagination-container">
            <!-- 分页信息 -->
            <el-pagination
              @size-change="handleSizeChangeFile"
              @current-change="handleCurrentChangeFile"
              :current-page.sync="fileQueryParams.pageNum"
              :page-size.sync="fileQueryParams.pageSize"
              small
              layout="total, prev, pager, next, jumper"
              :pager-count="5"
              :total="fileTotal"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
      <!-- 图片信息-->
      <el-col :span="7">
        <el-card style="height: 780px" v-loading="pictureLoading">
          <div slot="header" class="search-header">
            <div class="show_title" style="margin-bottom: 5px"> 图片列表：</div>
            <div class="button-group" style="margin-left: auto">
              <el-button type="primary" size="mini" @click="downloadFiles" v-if="downloadFlag">下载</el-button>
              <el-button type="primary" size="mini" @click="downloadChange" v-if="pictureList.length > 0">
                {{ downloadFlag ? '取消' : '批量下载' }}
              </el-button>
            </div>
          </div>
          <ul class="engs-container">
            <li v-for="(picture, index) in pictureList" :key="picture.id">
              <span class="eng-row" @click="selectPicture(picture)" @dblclick="doubleOpen(index)"
                    :class="{ selected: picture === selectedPicture }">
                <input type="checkbox" v-model="picture.selected" @click.stop="selectPictures(picture)" v-if="downloadFlag"/>
                <i class="folder-icon picture-folder-icon"></i>
                <span class="folder-name">{{ picture.pageindexNo }}</span>
              </span>
            </li>
          </ul>
          <div class="pagination-container">
            <!-- 分页信息 -->
            <el-pagination
              small
              @size-change="handleSizeChangePicture"
              @current-change="handleCurrentChangePicture"
              :current-page.sync="pictureQueryParams.pageNum"
              :page-size.sync="pictureQueryParams.pageSize"
              layout="total, prev, pager, next, jumper"
              :pager-count="5"
              :total="pictureTotal"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>

    </el-row>

    <el-row
      :gutter="10" style="margin-left: 5px; margin-top: 5px; margin-right: 5px">
      <el-card style="margin-left: 10px;margin-right: 10px">
        <el-row>
          <el-col :span="24">
            <eng-info
              :eng-info="selectedEng"
              @updateEngInfo="getEngList"
              :ifDel="ifDelete"
              v-if="showEngInfo"
            ></eng-info>
          </el-col>
        </el-row>
      </el-card>
    </el-row>

    <!--    <el-dialog-->
    <!--        :visible.sync="imgDialogVisible"-->
    <!--        title="文件详情"-->
    <!--        :width="dialogWidth"-->
    <!--        center-->
    <!--    >-->
    <!--      <div class="dialog-content">-->
    <!--        <div class="my_button">-->
    <!--          <el-button icon="el-icon-download" type="success" @click="downloadFile">下载</el-button>-->
    <!--&lt;!&ndash;          <el-button icon="el-icon-printer" type="primary">打印</el-button>&ndash;&gt;-->
    <!--          <el-button icon="el-icon-arrow-left" type="info" @click="previous">上一页</el-button>-->
    <!--          <el-button icon="el-icon-arrow-right" type="info" @click="next">下一页</el-button>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--      <embed :src="blobImage" type="image/jpeg" width="100%" height="1000px"/>-->
    <!--      &lt;!&ndash;      <img :src="blobImage" alt="图片" width="100%" height="auto" />&ndash;&gt;-->
    <!--    </el-dialog>-->
    <el-image-viewer v-if="imgDialogVisible" :zIndex="Number(99999)" :url-list="canvasList"
                     :on-close="closeImgViewer"/>

  </div>
</template>

<script>
import {listOldeeng} from "@/api/system/oldeeng";
import {listOldeanjuan} from "@/api/system/oldeanjuan";
import {listOldefile} from "@/api/system/oldefile";
import {downloadOldMore, downloadPic, getOldPic, listOldepicture} from "@/api/system/oldepicture";
import EngInfo from "@/views/system/e-dangan-old/engInfo.vue";

export default {
  components: {
    EngInfo,
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  data() {
    return {
      canvasList: [],
      engList: [], //工程列表
      anjuanList: [], //案卷列表
      fileList: [], //文件列表
      pictureList: [], //文件列表

      engTotal: 0, //工程总数
      anjuanTotal: 0, //案卷总数
      fileTotal: 0, //文件总数
      pictureTotal: 0, //文件总数
      showEngInfo: true, // 初始化时显示EngInfo组件
      ifDelete: 0,

      selectedEng: null,
      selectedAnJuan: null,
      selectedWenJian: null,
      selectedPicture: null,
      lastOpenedEngId: null,

      engQueryParams: {
        pageNum: 1,
        pageSize: 20,
        projectStatus: 0,
        gcName: null,
      },
      anjuanQueryParams: {
        gccreelGcno: null,
      },
      fileQueryParams: {
        pageNum: 1,
        pageSize: 20,
        gccatalogueGcno: null,   //工程号
        gccatalogueCreelno: null,   //案卷号
        gccatalogueName: null,
      },
      pictureQueryParams: {
        pageNum: 1,
        pageSize: 20,
        pageindexGcno: null,   //工程号
        pageindexCreelno: null,   //案卷号
        pageindexCatalogueno: null,   //文件号
      },
      picSwitch: false,
      engLoading: false,
      anjuanLoading: false,
      fileLoading: false,
      pictureLoading: false,

      openPicIndex: '',
      blobImage: "", //图片url
      imgDialogVisible: false, // 控制弹窗的显示与隐藏
      dialogWidth: "20vm", // 弹窗的宽度
      dialogHeight: "80vh",
      selectedPictures: [], // 存储被选中的文件的数组
      downloadFlag: false, //下载显示勾选框
    };
  },
  created() {
    this.getEngList();
  },
  methods: {
    //获取工程信息
    getEngList() {
      this.engLoading = true;
      listOldeeng(this.engQueryParams).then((response) => {
        setTimeout(() => {
          this.engList = response.rows;
          this.engTotal = response.total;
          this.engLoading = false;
        }, 300);
      }).catch((error) => {
        this.$message.error("获取工程信息失败:" + error);
        this.engLoading = false;
      });
    },

    searchEng() {
      this.fileList = [];
      this.fileTotal = 0;
      this.fileQueryParams.gccatalogueCreelno = null
      this.fileQueryParams.gccatalogueGcno = null
      this.fileQueryParams.gccatalogueName = null;
      this.pictureList = [];
      this.pictureTotal = 0;
      this.engQueryParams.pageNum = 1;
      this.getEngList();
    },
    resetEng() {
      this.engQueryParams.gcName = null;
      this.fileQueryParams.gccatalogueCreelno = null
      this.fileQueryParams.gccatalogueGcno = null
      // this.showEngInfo = false; // 隐藏EngInfo组件
      this.fileQueryParams.gccatalogueName = null;
      this.ifDelete = 1; // 增加 ifDelete 的值，触发子组件的 ifDel 属性变化
      // this.showEngInfo = false; // 隐藏EngInfo组件
      this.fileList = [];
      this.fileTotal = 0;
      this.pictureList = [];
      this.pictureTotal = 0;
      this.getEngList();
      // // 调用子组件的 reset 方法来重置子组件
      // this.$refs.engInfo.reset();
    },
    toggleEng(eng) {
      // 如果上次打开的目录不为空且不等于当前目录的id，则折叠上次打开的目录
      // console.log(this.engList)
      this.ifDelete = 0;
      this.pictureList = [];
      if (this.lastOpenedEngId !== null && this.lastOpenedEngId !== eng.id) {
        const lastOpenedEng = this.engList.find((item) => item.id === this.lastOpenedEngId);
        if (lastOpenedEng) {
          lastOpenedEng.expanded = false;
        }
      }
      // 更新lastOpenedEngId为当前目录的id
      this.lastOpenedEngId = eng.id;

      this.selectedEng = eng
      if (eng.expanded === undefined) {
        this.$set(eng, 'expanded', false);
        this.anjuanQueryParams.gccreelGcno = eng.gcNo;
        this.fileQueryParams.gccatalogueGcno = eng.gcNo
        this.pictureQueryParams.pageindexGcno = eng.gcNo
        this.getAnjuanList(eng);
      } else {
        eng.expanded = !eng.expanded;
      }
      // 将 showInfo 设置为 true，重新显示工程信息
      this.showEngInfo = true;
    },
    handleSizeChangeEng(pageSize) {
      this.engQueryParams.pageSize = pageSize;
      this.getEngList();
    },
    handleCurrentChangeEng(currentPage) {
      this.engQueryParams.pageNum = currentPage;
      this.getEngList();
    },
    //获取案卷信息
    getAnjuanList(eng) {
      this.anjuanLoading = true;
      this.fileList = [];
      console.log(this.anjuanQueryParams.gccreelGcno)
      listOldeanjuan(this.anjuanQueryParams).then((response) => {
        setTimeout(() => {
          eng.anjuanList = response.rows;
          this.anjuanTotal = response.total;
          eng.expanded = !eng.expanded;
          this.anjuanLoading = false;
        }, 300);
      }).catch((error) => {
        this.$message.error("获取案卷信息失败:" + error);
        this.anjuanLoading = false;
      });
    },
    selectanJuan(anJuan) {
      this.selectedAnJuan = anJuan;
      this.fileQueryParams.gccatalogueCreelno = anJuan.gccreelNo
      this.pictureQueryParams.pageindexCreelno = anJuan.gccreelNo
      this.pictureList = []
      this.pictureTotal = 0
      this.getFileList()
    },

    //获取文件信息
    getFileList() {
      this.fileLoading = true;
      listOldefile(this.fileQueryParams).then((response) => {
        setTimeout(() => {
          this.fileList = response.rows;
          this.fileTotal = response.total;
          this.fileLoading = false;
        }, 300);
      }).catch((error) => {
        this.$message.error("获取文件信息失败:" + error);
        this.fileLoading = false;
      });
    },
    selectFile(file) {
      this.selectedWenJian = file;
      this.pictureQueryParams.pageindexCatalogueno = file.gccatalogueNo
      this.getPictureList()
    },
    searchFile() {
      if (this.fileQueryParams.gccatalogueCreelno === null) {
        this.$message("请先选择案卷！")
      } else {
        this.pictureList = [];
        this.pictureTotal = 0;
        this.fileQueryParams.pageNum = 1;
        this.getFileList();
      }
    },
    resetFile() {
      this.fileQueryParams.gccatalogueName = null;
      if (this.fileQueryParams.gccatalogueCreelno === null) {
        this.$message("请先选择案卷！")
      } else {
        this.pictureList = [];
        this.pictureTotal = 0;
        this.getFileList();
      }
    },
    handleSizeChangeFile(pageSize) {
      this.fileQueryParams.pageSize = pageSize;
      this.getFileList();
    },
    handleCurrentChangeFile(currentPage) {
      this.fileQueryParams.pageNum = currentPage;
      this.getFileList();
    },

    //获取图片信息
    getPictureList() {
      this.pictureLoading = true;
      listOldepicture(this.pictureQueryParams)
        .then((response) => {
          setTimeout(() => {
            this.pictureList = response.rows;
            this.pictureTotal = response.total;
            this.pictureLoading = false;
          }, 300);
        })
        .catch((error) => {
          this.$message.error("获取图片信息失败:" + error);
          this.pictureLoading = false;
        });
    },
    selectPicture(picture) {
      this.selectedPicture = picture;
    },

    doubleOpen(index) {
      this.openPicIndex = index
      this.openPicture(this.openPicIndex)
    },
    async openPicture(index) {
      this.picSwitch = true;
      this.canvasList = [];
      for (let i = index; i < this.pictureList.length; i++) {
        this.fileForm = this.pictureList[i]; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
        await getOldPic(this.fileForm)
          .then((response) => {
            const blob = new Blob([response], {type: "image/jpeg"});
            this.blobImage = URL.createObjectURL(blob);
            this.canvasList.push(URL.createObjectURL(blob));
          })
          .catch((error) => {
            console.error("获取图片时出错:", error);
            // 可以添加错误处理逻辑，比如显示一个错误提示框等
          });
        if (this.picSwitch === false) {
          return;
        } else {
          this.imgDialogVisible = true; // 显示弹窗
        }
      }
      if (index !== 0) {
        for (let i = 0; i < index; i++) {
          if (this.picSwitch === false) {
            return;
          }
          this.fileForm = this.pictureList[i]; // 将文件信息保存到fileForm中，以便在getPdf函数中使用
          await getOldPic(this.fileForm)
            .then((response) => {
              const blob = new Blob([response], {type: "image/jpeg"});
              this.blobImage = URL.createObjectURL(blob);
              this.canvasList.push(URL.createObjectURL(blob));
            })
            .catch((error) => {
              console.error("获取图片时出错:", error);
            });
        }
      }
    },
    closeImgViewer() {
      this.picSwitch = false;
      this.canvasList = [];
      this.imgDialogVisible = false;
    },

    //选中多个文件
    selectPictures(picture) {
      // 如果文件已经选中，取消选中并从selectedPictures数组中移除
      const index = this.selectedPictures.findIndex(selectedPicture => selectedPicture.id === picture.id);
      if (picture.selected) {
        picture.selected = false;
        if (index !== -1) {
          this.selectedPictures.splice(index, 1); // 使用splice方法移除指定索引的元素
        }
      } else {
        // 如果文件未选中，选中并添加到selectedPictures数组中
        picture.selected = true;
        this.selectedPictures.push(picture);
      }
    },
    //展开/关闭下载
    downloadChange() {
      this.pictureList.forEach((file) => {
        file.selected = false; // 为每个数据对象添加selected属性，初始值为false
      });
      this.selectedPictures = [];
      this.downloadFlag = !this.downloadFlag;
    },
    // 下载单个文件
    downloadOnePicture(picture) {
      downloadPic(picture).then((response) => {
        const blob1 = new Blob([response], {type: "image/tiff"});
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob1);
        link.download = "file.tif";
        link.click();
      })
    },
    //下载多个文件
    downloadFiles() {
      console.log(this.selectedPictures)
      if (this.selectedPictures.length === 0) {
        this.$message({
          message: '请先选择要下载的文件！',
          type: 'warning'
        });
      } else if (this.selectedPictures.length === 1) {
        this.selectedPictures.forEach(picture => {
          this.downloadOnePicture(picture);
        })
      } else {
        let ids = [];
        this.selectedPictures.forEach(picture => {
          let newId = picture.id.replace(/\//g, "++");
          ids.push(newId)
        })
        console.log(ids)
        downloadOldMore(ids).then((response) => {
          // 处理接收到的二进制ZIP文件数据
          const blob = new Blob([response], {type: "application/zip"});
          const url = window.URL.createObjectURL(blob);
          // 创建一个下载链接并触发点击以下载ZIP文件
          const a = document.createElement('a');
          a.href = url;
          a.download = 'downloaded.zip';
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          this.selectedPictures = []; // 清除多选信息
        });
      }
    },

    handleSizeChangePicture(pageSize) {
      this.pictureQueryParams.pageSize = pageSize;
      this.getPictureList();
    },
    handleCurrentChangePicture(currentPage) {
      this.pictureQueryParams.pageNum = currentPage;
      this.getPictureList();
    },
  },
};
</script>

<style>
.search-header {
  display: flex;
  justify-content: space-between; /* 将内容分散对齐，使工程信息靠左，其他元素靠右 */
  align-items: center; /* 垂直居中对齐 */
}

.my_input {
  margin-left: auto;
  width: 10vw;
}

.show_title {
  flex-grow: 1; /* 工程目录占据剩余空间，将其靠左 */
}

.flex-container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}

.button-group {
  margin-left: 10px;
  display: flex;
  justify-content: center;
}

.engs-container {
  height: 600px;
  overflow-y: auto;
  padding: 10px;
  margin-top: -15px;
  border-radius: 4px;

}

.eng-row {
  flex-basis: 100%;
  margin-bottom: -2px;
  display: flex;
  align-items: center;
  padding: 6px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.anjuan-row {
  margin-left: -12px;
  margin-bottom: -2px;
  flex-basis: 100%;
  display: flex;
  align-items: center;
  padding: 6px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}


.eng-row:hover {
  background-color: rgba(204, 232, 255, 0.5);
}

.anjuan-row:hover {
  background-color: rgba(204, 232, 255, 0.5);
}

.pagination-container {
  margin-top: 10px;
}

.folder-icon {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  margin-right: 5px;
  background-size: cover;
}

.folder-name {
  flex-grow: 1;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.show_title {
  font-weight: bold;
  font-size: 20px;
  color: rgb(26, 115, 198);
}

/* 选中状态的样式 */
.selected {
  background-color: #cce8ff;
}

/* 不同图标的样式 */
.eng-folder-icon {
  background-image: url("~@/assets/icons/folder/eng.png");
}

.anJuan-folder-icon {
  background-image: url("~@/assets/icons/folder/anjuan.png");
}

.file-folder-icon {
  background-image: url("~@/assets/icons/folder/file.png");
}

.picture-folder-icon {
  background-image: url("~@/assets/icons/folder/picture.png");
}
</style>
